﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;

namespace Hackathon.Services
{
    public class PearsonLongamnDictionaryService
    {
        public const int MaxSentenceLength = 100;
        public const int MaxWords = 10;
        public const int MinWords = 3;
        public static WordDetails GetRandomWord()
        {
            WordDetails ret = null;
            
            while (ret == null || ret.Definition == null)
            {
                var req = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://api.pearson.com/longman/dictionary/entry/random.xml?apikey={0}", System.Configuration.ConfigurationManager.AppSettings["LongmanDictionaryKey"]));
                var resp = (HttpWebResponse)req.GetResponse();
                XmlDocument doc = new XmlDocument();
                doc.Load(resp.GetResponseStream());
                ret = new WordDetails(doc);
            }
            return ret;
        }

        public class WordDetails
        {
            public WordDetails() { }
            public WordDetails(XmlDocument doc)
            {
                id = doc.SelectSingleNode("/Entry").Attributes["id"].Value;
                Text = doc.SelectSingleNode("/Entry/Head/HWD").InnerText;
                foreach(XmlNode node in doc.SelectNodes("/Entry/Sense/DEF"))
                {
                    if (node.InnerText.Length > MaxSentenceLength)
                        continue;
                    string[] tmp = node.InnerText.Replace(",","").Replace(".","").Split(new char[]{' '});
                    if (MinWords > tmp.Length || tmp.Length > MaxWords)
                        continue;
                    Definition = tmp;
                    break;
                }
            }
            public string id { get; set; }
            public string Text { get; set; }
            public string [] Definition { get; set; }
        }
    }
}